package com.hengxinguotong.zhihuichengjian.ui.document;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.DocumentListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Document;
import com.hengxinguotong.zhihuichengjian.bean.DocumentRes;
import com.hengxinguotong.zhihuichengjian.bean.DocumentType;
import com.hengxinguotong.zhihuichengjian.bean.DocumentTypeRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectGroupPop;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 文档管理
 * Created by liux on 2017/5/2.
 */

public class DocumentManagementActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.state_select_tv)
    HXTextView stateSelectTv;
    @BindView(R.id.iv_p)
    ImageView ivP;
    @BindView(R.id.et_project)
    HXEditTextView etProject;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.document_lv)
    PullToRefreshListView documentLv;
    @BindView(R.id.add)
    HXTextView add;
    private DocumentListAdapter documentAdapter;
    private int pageIndex = 1;
    private List<Document> documents;
    private SelectGroupPop mSelectStatePop;
    public static List<DocumentType> documentTypeList;
    private int type = 1;
    private String documentId;
    private static final int MSG_UPDATE_INFO = 0x110;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_INFO:
                    if (documentLv != null) {
                        documentLv.setRefreshing();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document_management);
        ButterKnife.bind(this);
//        if (hasAdd()) {
//            add.setVisibility(View.VISIBLE);
//        }
        documentLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Document document = documents.get(position - 1);
                Intent intent = new Intent();
                if (document.getType() == 3) {
                    intent.setClass(DocumentManagementActivity.this, DocumentListActivity.class);
                }else if(document.getType() == 2){
                    intent.setClass(DocumentManagementActivity.this, DocumentMenuActivity.class);
                }
                intent.putExtra("document", document);
                startActivity(intent);
            }
        });
        documentLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getDocumentList(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getDocumentList(null);
            }
        });
        etProject.addTextChangedListener(searchTextWatcher);
        getDocumentList(getResources().getString(R.string.loading));
    }



    private TextWatcher searchTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mHandler.removeMessages(MSG_UPDATE_INFO);
            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_INFO, 500);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    private void getDocumentType() {
        RequestParams params = new RequestParams();
        Utils.requestData(getResources().getString(R.string.loading), this, "/dataManagement/queryType/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    DocumentTypeRes documentTypeRes = gson.fromJson(json, DocumentTypeRes.class);
                    documentTypeList = documentTypeRes.getValue();
                    if (documentTypeList != null && documentTypeList.size() > 0) {
                        getDocumentList(getResources().getString(R.string.loading));
                    } else {
                        showToast("获取文档类型失败");
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void getDocumentList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("pageNum", pageIndex);
            if (!Utils.isEmpty(etProject.getEditableText().toString())) {
                jsonObject.put("name", etProject.getEditableText().toString());
            }
            jsonObject.put("type", type + "");
            if(documentId != null && Utils.isEmpty(documentId)){
                jsonObject.put("id", documentId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/dataManagement/queryListByCtructionId/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (documentLv.isRefreshing()) {
                    documentLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    DocumentRes commonRes = gson.fromJson(json, DocumentRes.class);
                    addData(commonRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
                if (documentLv.isRefreshing()) {
                    documentLv.onRefreshComplete();
                }
            }
        });
    }


    private void addData(List<Document> datas) {
        if (pageIndex == 1) {
            if (datas.size() == 0) {
                showEmptyView(documentLv);
            } else {
                dismissEmptyView();
            }
            documents = datas;
            documentAdapter = new DocumentListAdapter(this, documents);
            documentLv.setAdapter(documentAdapter);
            if (datas.size() == Utils.ONCECOUNT) {
                documentLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            documents.addAll(datas);
            documentAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            documentLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1 && documentLv != null) {
            documentLv.setRefreshing();
        }
    }

    @OnClick({R.id.iv_back, R.id.state_select_tv, R.id.add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.state_select_tv:
                break;
            case R.id.add:
                startActivityForResult(new Intent(this, AddDocumentActivity.class), 1);
                break;
        }
    }

    public static String getDocumentTypeById(int id) {
        if (documentTypeList == null || documentTypeList.size() == 0) {
            return "未知";
        }
        for (int i = 0; i < documentTypeList.size(); i++) {
            DocumentType documentType = documentTypeList.get(i);
            if (id == documentType.getValue()) {
                return documentType.getName();
            }
        }
        return "未知";
    }

}
